<script lang="ts" setup generic="T extends Record<string, string | number>">
import { message } from 'ant-design-vue'
import type { AfterFetchContext } from '@vueuse/core'
import type { IBasic } from '~/types/apis/basic'
import type { ColumnsType } from 'ant-design-vue/es/table'
import type { ProjectTableNeeds } from '~/types/apis/project'
import type { NotifyFormState } from '~/types/apis/project'
import type notifyModal from '~/components/notifyModal.vue';

const props = withDefaults(
    defineProps<{
        baseName: string
        localizeName: string
        columns: ColumnsType<any>
        loadingWithGetDataSource: boolean
        customFields?: string[]
    }>(),
    {
        customFields: () => [],
    },
)

const globalConfig = useGlobalConfigStore()
const dataSource = defineModel<T[]>('dataSource', { required: true })

const { baseName } = toRefs(props)

const emits = defineEmits<{
    (e: 'refreshData'): void,
}>()

const { post: fetchUpdateProject } = useCustomFetch(
    `/engine-service/api/v1/${baseName.value}/update`,
    {
        immediate: false,
        afterFetch(ctx: AfterFetchContext<IBasic<any>>) {
            if (ctx.data && ctx.data.code === 0) {
                message.success(ctx.data.msg ?? '保存成功')
            }
            return ctx
        },
    },
)

const { post: fetchCreateProject } = useCustomFetch(
    `/engine-service/api/v1/${baseName.value}/save`,
    {
        immediate: false,
        afterFetch(ctx: AfterFetchContext<IBasic<any>>) {
            if (ctx.data && ctx.data.code === 0) {
                message.success(ctx.data.msg ?? '创建成功')
            }
            return ctx
        },
    },
)

const { post: fetchDeleteProject } = useCustomFetch(
    `/engine-service/api/v1/${baseName.value}/del`,
    {
        immediate: false,
        afterFetch(ctx: AfterFetchContext<IBasic<any>>) {
            if (ctx.data && ctx.data.code === 0) {
                message.success(ctx.data.msg ?? '删除成功')
            }
            return ctx
        },
    },
)

async function handleSave(instance: T, isNew?: boolean) {
    if (isNew) {
        await fetchCreateProject(instance).execute()
    } else {
        await fetchUpdateProject(instance).execute()
    }
    emits('refreshData')
}

function handleCreate() {
    dataSource.value.push({
        // eslint-disable-next-line unicorn/prefer-at
        id: Number(dataSource.value?.[dataSource.value.length - 1]?.id ?? 0) + 1,
        projectId: globalConfig.config.projectId,
    } as any)
}

async function handleDelete(instance: T) {
    let data = {}
    if(instance.notificationDTO){
        data = {
            id: instance.id,
            notificationId: instance.notificationDTO.id,
        }
    }else{
        data = {
            id: instance.id,
        }
    }
    await fetchDeleteProject(data).execute()
    emits('refreshData')
}

const notifyModalVisible = ref(false)
const notifySettingIndex = ref(-1)
const notificationDTO = ref({})
const handleNotifySetting = (index: number) => {
    notifySettingIndex.value = index
    if(dataSource.value[index]?.notificationDTO && dataSource.value[index]?.notificationDTO.id !== null){
        notificationDTO.value = dataSource.value[index]?.notificationDTO
    }else{
        notificationDTO.value = {}
    }
    notifyModalVisible.value = true
}

const saveNotify = async (form: NotifyFormState) => {
    notifyModalVisible.value = false
    let instance = dataSource.value[notifySettingIndex.value] as any
    delete instance.notificationDTO
    delete instance.projectAdmin
    delete instance.projectId
    form.id = instance.notificationId
    instance.notificationUpdateReq = form
    await fetchUpdateProject(instance).execute()
    emits('refreshData')
}

const cancelNotify = () => {
    notificationDTO.value = {}
}
</script>

<template>
    <div>
        <div flex items-center>
            <div class="colum"></div>
            <h1 my ml-4>{{ localizeName }}管理:</h1>
        </div>
        <notifyModal v-model:modalVisible="notifyModalVisible" @submit="saveNotify" @cancel="cancelNotify" :formData="notificationDTO"></notifyModal>

        <EditableTable v-model:data-source-proxy="dataSource" :loading="loadingWithGetDataSource"
            :custom-fields="customFields" :columns="columns" :base-name="baseName" @save="handleSave"
            @add-data="handleCreate" @delete="handleDelete" @notifySetting="handleNotifySetting" />
    </div>
</template>

<style>
.colum {
    width: 2px;
    height: 15px;
    background: #6F8DE9;
    border-radius: 16px 16px 16px 16px;
}
</style>
